<?php
/**
 * Created by laoyu.
 * User: hilaoyu@qq.com
 * Date: 2018/7/15
 * Time: 上午10:17
 */

namespace Hilaoyu\Utils;


class UtilSupport
{
    protected static $instance = [];

    /**
     * 传入类名，返回类的实例
     * @param $class_name
     * @return mixed
     */
    static public function makeClass($class_name){
        $args = func_get_args();

        array_shift($args);

        return new $class_name(...$args);
    }

    /**
     * 传入类名，返回类的实例(如果这个类已通过此方法实例过，则返回已有实例)
     * @param string $class_name
     * @return mixed
     */
    static public function makeClassSingle(string $class_name)
    {
        $args = func_get_args();

        if(!isset(static::$instance[$class_name])){
            static::$instance[$class_name] = static::makeClass(...$args);
        }
        return static::$instance[$class_name];
    }


    static public function runningInWindows(){
        return strtolower(substr(PHP_OS, 0, 3)) === 'win';
    }


    static public function tryQuiet(\Closure $callback,$default=null){

        $result = null;
        try{
            $result = @call_user_func($callback);
        }catch (\Exception $exception){
            if($default instanceof \Closure){
                $result = call_user_func($default,$exception);
            }else{
                $result = $default;
            }
        }finally{
            return $result;
        }


        return $result;
    }


    /**
     * @param \Closure $callback
     * @param int $step 执行间隔时间
     * @param int $times 执行次数
     */
    static public function reTry(\Closure $callback,$step=30,$times=3){
        $times = intval($times);
        do{
            if(true === call_user_func($callback)){
                break;
            }
            $times--;
            sleep($step);
        }while($times >0);
    }

}
